package com.example.demo_one.adpter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.demo_one.R
import com.example.demo_one.model.CityData

class MyAdapter(private val item: List<CityData>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
    /**
     * ViewHolder类，用于缓存视图项中的控件
     * @param view 单项视图布局
     */
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        // val textView: TextView = view.findViewById(R.id.item_text)
        val imageView: ImageView = view.findViewById(R.id.cityIcon)
        val textView: TextView = view.findViewById(R.id.cityText)
        val introView: TextView = view.findViewById(R.id.cityIntro)
    }

    /**
     * 创建或加载ViewHolder对象，并返回
     * @param parent 父布局
     * @param viewType 视图类型
     * @return ViewHolder对象
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        // 加载本地xml
        val inflater =
            LayoutInflater.from(parent.context).inflate(R.layout.item_city_plus, parent, false)
        return ViewHolder(inflater)
    }

    /**
     * 获取数据项的数量
     * @return 数据项的数量
     */
    override fun getItemCount(): Int {
        return item.size
    }

    /**
     * 绑定数据到ViewHolder对象中
     * @param holder ViewHolder对象
     * @param position 当前项的位置
     */
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val cityData = item[position]
        holder.imageView.setImageResource(cityData.icon)
        holder.textView.text = cityData.text
        holder.introView.text = cityData.intro
    }
}